package com.kcloud.commons.tools.codebuilder.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kcloud.commons.tools.codebuilder.CodeBuilder;
import com.kcloud.commons.tools.codebuilder.CodeBuilderConfig;
import com.kcloud.commons.tools.codebuilder.toolkit.DBTable;
import com.kcloud.jpa.repository.KCloudJpaEntityRepository;
import com.squareup.javapoet.*;
import lombok.AllArgsConstructor;
import lombok.Data;

import javax.sql.DataSource;

/**
 * @author songhuiqing
 */
@Data
@AllArgsConstructor
public class JpRepositoryCodeBuilder implements CodeBuilder {
    private static final String nameSuffix = "Repository";
    private CodeBuilderConfig config;

    @Override
    public DataSource getDataSource() {
        return config.getDataSource();
    }

    @Override
    public JavaFile generateJavaFile(DBTable table) {
        //生成一个java的实体对象
        String withoutPrefixTableName = table.getName();
        if (config.isIgnorePrefix() && withoutPrefixTableName.toLowerCase().contains(config.getPrefix().toLowerCase())) {
            withoutPrefixTableName = StringUtils.removePrefixAfterPrefixToLower(table.getName(), config.getPrefix().length());
        }
        String entityName = StringUtils.capitalize(StringUtils.underlineToCamel(withoutPrefixTableName));
        Class<?> entityClass;
        try{
            entityClass = getEntityClass(entityName);
        }catch (ClassNotFoundException e) {
            throw new RuntimeException("请先生成实体类对象");
        }
        TypeSpec typeSpec = TypeSpec.interfaceBuilder(entityName + nameSuffix)
                .addSuperinterface(ParameterizedTypeName.get(KCloudJpaEntityRepository.class, entityClass))
                .build();
        return JavaFile.builder(String.format("%s.%s", config.getPackagePath(), repositoryBasePackage), typeSpec).build();
    }

    private Class<?> getEntityClass(String entityName) throws ClassNotFoundException{
        return Class.forName(String.format("%s.%s.%s", config.getPackagePath(), entityBasePackage, entityName));
    }
}
